package com.example.stock.ui.main;

import android.annotation.SuppressLint;
import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

import com.example.stock.base.BaseViewModel;
import com.example.stock.base.Result;
import com.example.stock.config.Config;
import com.example.stock.http.ApiException;
import com.example.stock.http.ResponseCallback;
import com.example.stock.model.GoodsOrderBean;
import com.example.stock.util.DBUtil;
import com.example.stock.util.SharedPreferencesUtils;
import com.example.stock.util.Utils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class MainViewModel extends BaseViewModel {

    public MutableLiveData<Result<Object>> clearResult = new MutableLiveData<>();
    public MutableLiveData<Boolean> hasResult = new MutableLiveData<>();

    public MainViewModel(@NonNull Application application) {
        super(application);
    }

    /**
     * 1.	到货单同步接口, PDA主动请求NC实时获取到货单信息
     */
    public void getArriveOrder() {
        Map<String, String> map = new HashMap<>();
        String xmlStr = Utils.getRequestXml("getArriveorder", map, Config.SOAP_1_2);
        api.getArriveOrder12(xmlStr).enqueue(new ResponseCallback<String>(this) {
            @Override
            public void onSuccess(String o){
                if(!TextUtils.isEmpty(o) && o.contains("soap:Envelope")){
                    String res = Utils.analysisFault(o, "return");
                    String s = res.replaceAll("&lt;", "<").replaceAll("&gt;",">");
                    String resData = Utils.analysisFault(s, "data");
                    List<GoodsOrderBean> orderBeans = new Gson().fromJson(resData, new TypeToken<List<GoodsOrderBean>>(){}.getType());
                    if(orderBeans != null){
                        Log.d("wyj", "orderBean:" + orderBeans.size());
                        boolean insetEX = DBUtil.getInstance().insetEX(orderBeans);
                        if (insetEX) {
                            SharedPreferencesUtils.setDownloadFinish(true);
                            hasResult.setValue(true);
                        } else {
                            hasResult.setValue(false);
                            Utils.getInstance().showToast("数据保存失败，请重新请求数据");
                        }
                    } else {
                        hasResult.setValue(false);
                        Utils.getInstance().showToast("请求数据为空！");
                    }
                }
            }

            @Override
            public void onFailure(ApiException e) {
                super.onFailure(e);
                String message = e.getMessage();
                if(TextUtils.isEmpty(message)){
                    return;
                }
                assert message != null;
                if(message.contains("soap:Envelope")){
                    message = Utils.analysisFault(message, "faultstring");
                }
                Utils.getInstance().showToast(message);
            }
        });
        /*api.getArriveOrder().enqueue(new ResponseCallback<String>(this) {
            @Override
            public void onSuccess(String res) {
                List<GoodsOrderBean> list = new Gson().fromJson(res, new TypeToken<List<GoodsOrderBean>>() {
                }.getType());
                boolean insetEX = DBUtil.getInstance().insetEX(list);
                if (insetEX) {
                    SharedPreferencesUtils.setDownloadFinish(true);
                } else {
                    Utils.getInstance().showToast("数据保存失败，请重新请求数据");
                }
            }

            @Override
            public void onFailure(ApiException e) {
                super.onFailure(e);
                Utils.getInstance().showToast(e.getMessage());
                String res = "[{\n" +
                        "\t\"djh\": \"DH220126008\",\n" +
                        "\t\"dhrq\": \"2022-01-17\",\n" +
                        "\t\"gysCode\": \"064003\",\n" +
                        "\t\"gysName\": \"昆山普清净化科技有限公司\",\n" +
                        "\t\"memo\": \"后处理3月份物资请购\",\n" +
                        "\t\"dataList\": [{\n" +
                        "\t\t\"invcode\": \"20010101\",\n" +
                        "\t\t\"invname\": \"包装箱\",\n" +
                        "\t\t\"invspec\": \"-60*6 GB704\",\n" +
                        "\t\t\"hgsl\": \"1000.00000000\"\n" +
                        "\t}, {\n" +
                        "\t\t\"invcode\": \"20010102\",\n" +
                        "\t\t\"invname\": \"包装箱2\",\n" +
                        "\t\t\"invspec\": \"-60*6 GB704\",\n" +
                        "\t\t\"hgsl\": \"1000.00000000\"\n" +
                        "\t}]\n" +
                        "}]";
                onSuccess(res);
            }
        });*/
    }

    @SuppressLint("CheckResult")
    public void clearDB() {
        getShowDialog().setValue(true);
        Observable.just(1).map(new Function<Integer, Boolean>() {
            @Override
            public Boolean apply(Integer integer) throws Exception {
                return DBUtil.getInstance().clearAll();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        getShowDialog().setValue(false);
                        Result<Object> result = new Result<>();
                        if (aBoolean) {
                            result.setCode("0001");
                            result.setMsg("清除本地数据成功");
                        } else {
                            result.setCode("0002");
                            result.setMsg("清除本地数据失败，请重新清理");
                        }
                        clearResult.setValue(result);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        getShowDialog().setValue(false);
                        Result<Object> result = new Result<>();
                        result.setCode("0003");
                        result.setMsg(throwable.getMessage());
                        clearResult.setValue(result);
                    }
                });
    }

    /**
     * 获取天气.
     */
    public void getWeather(String city) {
        Map<String, String> map = new HashMap<>();
        map.put("theCityName", city);
        String xmlStr = Utils.getRequestXml("getWeatherbyCityName", map, Config.SOAP_1_2);
        api.getWeather12(xmlStr).enqueue(new ResponseCallback<String>(this) {
            @Override
            public void onSuccess(String o) {
            }
        });
    }
}